package com.lingfengerick.commons.encrypt.sm4tool;

import com.lingfengerick.commons.encrypt.sm4tool.toolkit.SM4Base;
import com.lingfengerick.commons.encrypt.sm4tool.toolkit.SM4_Context;

import java.util.Base64;

/**
 * @author lingfengerick
 * @since 2022/9/20 15:24
 */
public class ECBSecretStrategy extends SM4SecretStrategy{

    /**
    *
    * @author  lingfengerick
    * @since  2022/9/20  15:24
    * @param sm4Context SM4上下文
    * @param dataStr 数据
    * @param publicKey 密钥
    * @return 加密后的串
    *
    */
    @Override
    byte[] getEncryptedByte(SM4_Context sm4Context, String dataStr, String publicKey){
        try {
            byte[] keyBytes;
            if (HEX_STRING) {
                keyBytes = hexStringToBytes(publicKey);
            } else {
                keyBytes = publicKey.getBytes();
            }
            SM4Base sm4 = new SM4Base();
            sm4.sm4_setkey_enc(sm4Context, keyBytes);
            return sm4.sm4_crypt_ecb(sm4Context, dataStr.getBytes());
        } catch (Exception e) {
            return null;
        }
    }

    /**
    * 
    * @author  lingfengerick
    * @since  2022/9/20  16:05
    * @param sm4Context SM4上下文
    * @param encryptDataStr 加密数据
    * @param privateKey 密钥
    * @return 解密数组
    *
    */
    @Override
    byte[] getDecryptedByte(SM4_Context sm4Context ,String encryptDataStr , String privateKey) {
        try {
            byte[] keyBytes;
            if (HEX_STRING) {
                keyBytes = hexStringToBytes(privateKey);
            } else {
                keyBytes = privateKey.getBytes();
            }
            SM4Base sm4 = new SM4Base();
            sm4.sm4_setkey_dec(sm4Context, keyBytes);
            return sm4.sm4_crypt_ecb(sm4Context, Base64.getDecoder().decode(encryptDataStr));
        } catch (Exception e) {
            return null;
        }
    }
}
